package com.DosonLeung.homeschoolcommunication.Utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;

import org.apache.http.util.EncodingUtils;
import org.json.JSONArray;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by DosonLeung on 2014/10/21.
 */
public class StorageUtil {
    public static String baseFileName = "HSC";
    public static String chatFileName = "chat";
    public static String cameraFileName = "camera";
    public static String voiceFileName = "audio";
    public static String infoFileName = "info";

    private static final File baseDir = new File(Environment.getExternalStorageDirectory() + "/"+baseFileName+"/");
    private static final File chatDir = new File(baseDir+"/"+chatFileName+"/");
    private static final File cameraDir = new File(baseDir+"/"+cameraFileName+"/");
    private static final File voiceDir = new File(baseDir+"/"+voiceFileName+"/");
    private static final File infoDir = new File(baseDir+"/"+infoFileName+"/");

    public static File getBaseDir() {
        return baseDir;
    }

    public static File getChatDir() {
        return chatDir;
    }

    public static File getCameraDir() {
        return cameraDir;
    }

    public static File getVoiceDir() {
        return voiceDir;
    }

    public static File getInfoDir() {
        return infoDir;
    }

    public static boolean fileExists(String url) {
        try {
            File f = new File(baseDir, url);
            return f.exists();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String saveMediaRecorderInVoice(MediaRecorder voiceRecorder,String fileName){
        String url = StorageUtil.getVoiceDir().toString() + fileName;
        File audioPath = new File(voiceDir.toString());
        if (!fileExists(audioPath.toString())) {
            audioPath.mkdir();
        }
        voiceRecorder.setOutputFile(url);
        return url;
    }

    public static boolean saveAsImage(String filename, Bitmap bitmap) {
        String en = Environment.getExternalStorageState();
        if (en.equals(Environment.MEDIA_MOUNTED)) {
            try {
                if (!fileExists("/"+cameraDir.toString()+"/"+filename)) {
                    cameraDir.mkdirs();
                    File file = new File(cameraDir, filename);
                    OutputStream out = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                    out.close();
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        } else {
            return false;
        }
    }

    public static String copyAsImage(String sourcePath,String fileName){
        String en = Environment.getExternalStorageState();
        if (en.equals(Environment.MEDIA_MOUNTED)) {
            try {
                File sourceFile = new File(sourcePath);
                File toFile = new File(cameraDir, fileName);
                Bitmap bitmap;
                if (!sourceFile.exists()) {
                    cameraDir.mkdirs();
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(sourcePath, options);
                    options.inSampleSize = ImageUtil.computeSampleSize(options, -1, 128 * 128);
                    options.inJustDecodeBounds = false;
                    try {
                        bitmap = BitmapFactory.decodeFile(sourcePath, options);
                        OutputStream out = new FileOutputStream(toFile);
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                        out.close();
                    } catch (OutOfMemoryError e) {
                        e.printStackTrace();
                    }
                }
                return toFile.getAbsolutePath();
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        } else {
            return "";
        }
    }

    //实现把二进制文件读进相册
    public static boolean saveImageInAlbum(String target,String time,byte[]... data) {
        String en = Environment.getExternalStorageState();
        if (en.equals(Environment.MEDIA_MOUNTED)) {
            try {
                cameraDir.mkdirs();
                File file = new File (cameraDir,target+time);
                OutputStream out = new FileOutputStream(file);
                out.write(data[0]);
                out.flush();
                out.close();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        } else {
            return false;
        }
    }

    public static boolean saveAsJson(File Dir , String filename , String content) {
        String en = Environment.getExternalStorageState();
        if (en.equals(Environment.MEDIA_MOUNTED)) {
            try {
                if(!baseDir.exists())
                    baseDir.mkdirs();
                if(!Dir.exists())
                    Dir.mkdirs();
                File file = new File(Dir, filename+".json");
                OutputStream out = new FileOutputStream(file);
                out.write(content.getBytes());
                out.close();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("LoginActivity","保存文件失败");
                //return saveAsJson(Dir,filename,content);
                return false;
            }
        } else {
            return false;
        }
    }

    public static String retrieveFromFile(File Dir , String filename) {
        String result = null;
        try {
            File file = new File(Dir + "/" + filename);
            if (!file.exists()) {
                return (new JSONArray().toString());
            }
            InputStream in = null;
            in = new FileInputStream(file);
            int length = (int) file.length();
            byte[] temp = new byte[length];
            in.read(temp, 0, length);
            in.close();
            result = EncodingUtils.getString(temp, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    //清空文件内容
    public static void clearFile(File Dir,String fileName){
        try {
            File file = new File(Dir.toString() + "/" + fileName);
            FileWriter fw = new FileWriter(file);
            fw.write("");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除单个文件
    public static void deleteFile(String filePath){
        if(filePath!=null) {
            try {
                File file = new File(filePath);
                if (file.exists())
                    file.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //删除单个文件或者文件夾
    public static boolean deleteFileFolder(String delpath) {
        try {
            File file = new File(delpath);
            if (!file.isDirectory()) {
                file.delete();
            } else if (file.isDirectory()) {
                String[] filelist = file.list();
                for (int i = 0; i < filelist.length; i++) {
                    File delfile = new File(delpath + File.separator + filelist[i]);
                    if (!delfile.isDirectory()) {
                        delfile.delete();
                        System.out.println(delfile.getAbsolutePath() + "删除文件成功");
                    } else if (delfile.isDirectory()) {
                        deleteFileFolder(delpath + File.separator + filelist[i]);
                    }
                }
                System.out.println(file.getAbsolutePath()+"删除成功");
                file.delete();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    //第一次登陆返回false,其他登陆情况返回true
    public static boolean checkStatus(Activity app) {
        SharedPreferences preferences = app.getSharedPreferences("user", Context.MODE_PRIVATE);
        boolean status = preferences.getBoolean("status", false);
        SharedPreferences.Editor editor = preferences.edit();
        editor.clear();
        editor.putBoolean("status", true);
        editor.commit();
        return status;
    }
}
